<template>
  <div class="do-exam">
    <div class="exam-main">
      <!-- 考试信息栏 -->
      <div class="exam-header">
        <el-card>
          <div class="header-content">
            <div class="exam-info">
              <h2>{{ examInfo.examName }}</h2>
              <p class="description">{{ examInfo.description }}</p>
            </div>
            <div class="timer">
              <el-tag type="success" size="large">
                剩余时间：{{ formatTime(remainingTime) }}
              </el-tag>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 主要内容区 -->
      <div class="main-content">
        <!-- 题目导航 -->
        <div class="question-nav">
          <el-card>
            <template #header>
              <div class="nav-header">
                <span>题目导航</span>
                <span class="progress">{{ currentIndex + 1 }}/{{ questions.length }}</span>
              </div>
            </template>
            <div class="nav-buttons">
              <el-button v-for="(q, index) in questions" :key="index" :type="getQuestionButtonType(index)"
                @click="currentIndex = index">
                {{ index + 1 }}
              </el-button>
            </div>
          </el-card>
        </div>

        <!-- 答题区域 -->
        <div class="question-area">
          <el-card v-loading="loading" class="">
            <template v-if="currentQuestion">
              <div class="question-all">
                <div class="question-main">
                  <!-- 题目信息 -->
                  <div class="question-header">
                    <span class="question-type">{{
                      getTypeText(currentQuestion.typeId)
                    }}</span>
                    <span class="question-score">({{ currentQuestion.score }}分)</span>
                  </div>

                  <!-- 题目内容 -->
                  <div class="question-content">
                    {{ currentQuestion.content }}
                  </div>

                  <!-- 答题区域 -->
                  <div class="answer-area">
                    <!-- 单选题 -->
                    <template v-if="currentQuestion.typeId === 10001">
                      <el-radio-group v-model="answers[currentIndex]">
                        <el-radio v-for="(option, key) in JSON.parse(
                          currentQuestion.options
                        )" :key="key" :value="key">
                          {{ key }}. {{ option }}
                        </el-radio>
                      </el-radio-group>
                    </template>

                    <!-- 多选题 -->
                    <template v-if="currentQuestion.typeId === 10002">
                      <el-checkbox-group v-model="answers[currentIndex]">
                        <el-checkbox v-for="(option, key) in JSON.parse(
                          currentQuestion.options
                        )" :key="key" :value="key">
                          {{ key }}. {{ option }}
                        </el-checkbox>
                      </el-checkbox-group>
                    </template>

                    <!-- 判断题 -->
                    <template v-if="currentQuestion.typeId === 10003">
                      <el-radio-group v-model="answers[currentIndex]">
                        <el-radio value="true">正确</el-radio>
                        <el-radio value="false">错误</el-radio>
                      </el-radio-group>
                    </template>

                    <!-- 填空题 -->
                    <template v-if="currentQuestion.typeId === 10004">
                      <el-input v-model="answers[currentIndex]" type="textarea" :rows="3" placeholder="请输入答案" />
                    </template>

                    <!-- 简答题 -->
                    <template v-if="currentQuestion.typeId === 10005">
                      <el-input v-model="answers[currentIndex]" type="textarea" :rows="6" placeholder="请输入答案" />
                    </template>
                  </div>
                </div>
                <!-- 操作按钮 -->
                <div class="question-actions">
                  <el-button @click="handleAnswerSubmit" type="primary">保存答案</el-button>
                  <el-button v-if="currentIndex > 0" @click="currentIndex--">上一题</el-button>
                  <el-button v-if="currentIndex < questions.length - 1" @click="currentIndex++">下一题</el-button>
                  <el-button v-else type="success" @click="handleExamSubmit">提交试卷</el-button>
                </div>
              </div>
            </template>
          </el-card>
        </div>
      </div>

      <!-- 提交确认对话框 -->
      <el-dialog v-model="submitDialogVisible" title="确认提交" width="30%">
        <div class="submit-dialog">
          <p v-if="getUnansweredCount() !== 0">
            您还有 {{ getUnansweredCount() }} 题未作答，确定要提交试卷吗？
          </p>
          <p v-else>已作答全部题目，确定要提交试卷吗？</p>

          <div class="submit-actions">
            <el-button @click="submitDialogVisible = false">继续答题</el-button>
            <el-button type="primary" @click="confirmSubmit">确认提交</el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { examApi } from "../../api/examApi";
import { getTypeText } from "../../utils/utils";
import { questionApi } from "../../api/questionApi";

const route = useRoute();
const router = useRouter();
const examId = route.params.id;
const loading = ref(false);
const examInfo = ref({});
const questions = ref([]);
const answers = ref([]);
const currentIndex = ref(0);
const isSubmit = ref([]);
const remainingTime = ref(0);
const submitDialogVisible = ref(false);
let timer = null;

// 当前题目
const currentQuestion = computed(() => questions.value[currentIndex.value]);

const beginExam = async () => {
  try {
    await examApi.beginExam(examId);
  } catch (error) {
    router.push("/exam/" + examId);
  }
}

// 获取考试信息
const getExamInfo = async () => {
  try {
    const res = await examApi.getExamInfo(examId);
    examInfo.value = res.result.examInfo;
    questions.value = res.result.questions;
    answers.value = new Array(questions.value.length).fill();
    isSubmit.value = new Array(questions.value.length).fill(0);
    remainingTime.value = res.result.remainingTime;
    startTimer();
  } catch (error) {
    console.error("获取考试信息失败:", error);
    ElMessage.error("获取考试信息失败");
    router.push("/exam");
  }
};

// 开始计时器
const startTimer = () => {
  timer = setInterval(() => {
    if (remainingTime.value > 0) {
      remainingTime.value--;
    } else {
      clearInterval(timer);
      ElMessage.error("考试已结束");
      router.push("/exam/" + examId);
    }
  }, 1000);
};

// 格式化时间
const formatTime = (seconds) => {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = seconds % 60;
  return `${hours.toString().padStart(2, "0")}:${minutes
    .toString()
    .padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;
};

// 获取题目按钮类型
const getQuestionButtonType = (index) => {
  if (index === currentIndex.value) return "primary";
  if (answers.value[index]) return "success";
  return "info";
};

// 获取未答题数量
const getUnansweredCount = () => {
  return answers.value.filter(
    (answer) => !answer || (Array.isArray(answer) && answer.length === 0)
  ).length;
};

// 保存答案
const handleAnswerSubmit = async () => {
  try {
    await questionApi.saveAnswer({
      questionId: currentQuestion.value.questionId,
      examId: examId,
      paperId: currentQuestion.value.paperId,
      fullScore: currentQuestion.value.score,
      answer:
        currentQuestion.value.typeId === 10002
          ? JSON.stringify(answers.value[currentIndex.value])
          : answers.value[currentIndex.value],
    });
    ElMessage.success("保存成功");
  } catch (error) {
    console.error("保存试卷失败:", error);
  }
};
// 提交试卷
const handleExamSubmit = () => {
  submitDialogVisible.value = true;
};

// 确认提交
const confirmSubmit = async () => {
  try {
    // 生成问题-答案映射列表
    const data = questions.value.map((question, index) => ({
      examId: examId,
      paperId: currentQuestion.value.paperId,
      questionId: question.questionId,
      fullScore: question.score,
      answer:
        question.typeId === 10002
          ? JSON.stringify(answers.value[index] || [])
          : answers.value[index] || "",
    }));
    await questionApi.saveAllAnswer(data);
    await examApi.submitExam(examId);
    ElMessage.success("提交成功");
    router.push("/exam");
  } catch (error) {
    console.error("提交试卷失败:", error);
  }
};

// 页面关闭前提示
const handleBeforeUnload = (e) => {
  e.preventDefault();
  e.returnValue = "";
};

onMounted(() => {
  beginExam();
  getExamInfo();
  window.addEventListener("beforeunload", handleBeforeUnload);
});

onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
  window.removeEventListener("beforeunload", handleBeforeUnload);
});
</script>

<style scoped>
.do-exam {
  background-color: #f5f7fa;
  min-height: 100vh;
  overflow: hidden;
  /* 阻止水平滚动 */
}

.exam-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.exam-info h2 {
  margin: 0 0 10px 0;
}

.description {
  color: #606266;
  margin: 0;
}

.main-content {
  display: grid;
  grid-template-columns: 200px 1fr;
  gap: 20px;
}

.question-all {
  display: flex;
  min-height: 500px;
  flex-direction: column;
  justify-content: space-between;
}

.question-nav {
  position: sticky;
  top: 20px;
}

.nav-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.progress {
  color: #909399;
  font-size: 14px;
}

.nav-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.nav-buttons .el-button {
  width: 10px;
  margin-left: 0;
}

.question-header {
  margin-bottom: 20px;
}

.question-type {
  color: #409eff;
  margin-right: 10px;
}

.question-score {
  color: #f56c6c;
}

.question-content {
  font-size: 16px;
  line-height: 1.6;
  margin-bottom: 30px;
}

.answer-area {
  margin-bottom: 30px;
}

.question-actions {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.submit-dialog {
  text-align: center;
}

.submit-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 20px;
}

:deep(.el-radio),
:deep(.el-checkbox) {
  display: block;
  margin-bottom: 15px;
  margin-left: 0 !important;
}
</style>
